import router from "@/utils/router";
import NProgress from "nprogress";
import { useUserStore } from '@/utils/stores/modules/user'
import 'nprogress/nprogress.css'
import { PageEnum } from "@/utils/enums/pageEnums";
import { findFirstValidRoute } from "@/utils/router";
import { clearAuthInfo } from "@/utils/auth";
import { INDEX_ROUTE , INDEX_ROUTE_NAME } from "@/utils/router/routes";
import { isExternal } from "@/utils/common";
const loginPath = PageEnum.LOGIN
const notFoundPath = PageEnum.NOT_FOUND
// 白名单
const whiteList: string[] = [loginPath, notFoundPath]

console.log('Permission file loaded');


// 动态添加路由-使用递归进行调整-（fix: 修复之前超过3级菜单导致使用keep-alive功能无效问题
const addRoutesRecursively = (routes: any, parentPath = '') => {
    try {
        routes.forEach((route: any) => {
            // 如果路由是外部链接，则不添加
            if (isExternal(route.path)) {
                return
            }

            // 拼接父路由路径和当前路由路径
            const fullPath = parentPath + route.path

            // 创建路由对象，确保每个路由都有唯一的名称
            const routerEntry = {
                ...route,
                path: fullPath,
                name: route.name || fullPath.replace(/\//g, '_').replace('_', '') // 替换斜杠为下划线，生成唯一名称
            }

            // 添加路由
            if (!route.children) {
                router.addRoute(INDEX_ROUTE_NAME, routerEntry)
            } else {
                router.addRoute(routerEntry)
            }

            // 递归处理子路由
            if (route.children && route.children.length > 0) {
                addRoutesRecursively(route.children, fullPath + '/')
            }
        })
    } catch (e) {
        console.error('Error adding routes:', e)
    }
}

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const userStore = useUserStore()

    document.title =  to.meta.title as string +   ' - 后台管理系统'
    if (whiteList.includes(to.path)) {
        next()
    } else if (userStore.token) {
        const hasGetUserInfo = Object.keys(userStore.userInfo).length !== 0
        if (hasGetUserInfo) {
            if (to.path === PageEnum.LOGIN) {
                next({ path: loginPath })
            } else {
                next();
            }
        } else {

            try {
                await userStore.getUserInfo();
                const routes = userStore.routes;
                const routeName = findFirstValidRoute(routes);
                if (!routeName) {
                    clearAuthInfo()
                    next(notFoundPath);
                    return;
                }

                INDEX_ROUTE.redirect = { name: routeName }
                console.log(routeName)
                router.addRoute(INDEX_ROUTE)
                console.log(routes)
                routes.forEach((route: any) => {
                    if (isExternal(route.path)) {
                        return;
                    }
                    if(!route.children || route.children.length === 0){
                        router.addRoute(INDEX_ROUTE_NAME , route)
                    }

                    router.addRoute(route)
                })
                console.log("hello")
                next({ ...to, replace: true })
            } catch (error) {
                console.log("error")
                clearAuthInfo()
                next({ path: loginPath, replace: true ,query :{redirect : to.fullPath}})
            }
            // 判断是否首次进入首页（比如 path === '/' 或 name === 'index'）
            // if (to.path === '/' || to.name === 'index') {
            //     next({ path: '/adminapi/system/workbench'})
            // }else{
            //     next({ path: to.fullPath, replace: true })
            // }

        }
    } else {
        console.log('没有token')
        next({ path: loginPath, query: { redirect: to.fullPath } })
    }
})

router.afterEach(() => {
    NProgress.done()
})

export default router
